package de.tuhh.simsearch.model.persistence.usermgmt.entities;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToMany;

/**
 * Entity implementation class for the role entity. The role entity represents a role in the user management database.
 * The role entity has a name, a role description and a set of users which have this role. Used roles are at the moment
 * 'USERS' and 'ADMIN'.
 * 
 * @author SimSearch 1
 * 
 * @see UserEntity
 */
@Entity
public class RoleEntity implements Serializable {

  private static final long serialVersionUID = 1L;

  @Id private String roleName;

  private String groupDesc;

  @ManyToMany(mappedBy = "roles", cascade = CascadeType.PERSIST) private Set<UserEntity> users = new HashSet<UserEntity>();

  protected RoleEntity() {

  }

  /**
   * The class constructor, sets a role name for the entity
   * 
   * @param roleName
   *          the name of the role
   */
  public RoleEntity(String roleName) {

    this.roleName = roleName;
  }

  /**
   * Gets the set of users who have this role.
   * 
   * @return the set of users
   */
  public Set<UserEntity> getUsers() {

    return users;
  }

  /**
   * Adds a user to the set of users who have this role
   * 
   * @param u
   *          the user entity to add
   */
  public void addUser(UserEntity u) {

    this.users.add(u);
    if (!(u.getRoles().contains(this))) {

      u.addRole(this);
    }
  }

  /**
   * Removes a user from the set of users who have this role
   * 
   * @param u
   *          the user entity to remove
   */
  public void removeUser(UserEntity u) {

    this.users.remove(u);
    if (u.getRoles().contains(this)) {
      u.removeRole(this);
    }
  }

  protected void setUsers(Set<UserEntity> users) {

    this.users = users;
  }

  /**
   * Gets the name of the role
   * 
   * @return the name of the role
   */
  public String getRoleName() {

    return roleName;
  }

  /**
   * Sets the name of the role
   * 
   * @param name
   *          the name of the role
   */
  public void setRoleName(String name) {

    this.roleName = name;
  }

  /**
   * Gets the description of this role
   * 
   * @return the description of this role
   */
  public String getGroupDesc() {

    return groupDesc;
  }

  /**
   * Sets the description for this role
   * 
   * @param groupDesc
   *          the description for the role
   */
  public void setGroupDesc(String groupDesc) {

    this.groupDesc = groupDesc;
  }

}
